package drds.plus.parser.parser.dml;

import drds.plus.parser.abstract_syntax_tree.expression.Expression;
import drds.plus.parser.abstract_syntax_tree.expression.Pair;
import drds.plus.parser.abstract_syntax_tree.expression.primary.misc.Identifier;
import drds.plus.parser.abstract_syntax_tree.statement.UpdateStatement;
import drds.plus.parser.abstract_syntax_tree.statement.select.table.ITable;
import drds.plus.parser.lexer.Lexer;
import drds.plus.parser.lexer.Token;
import drds.plus.parser.parser.ExpressionParser;

import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;


public class UpdateParser extends DmlParser {

    public UpdateParser(Lexer lexer, ExpressionParser expressionParser) {
        super(lexer, expressionParser);
    }


    public UpdateStatement update() {
        match(Token.KW_UPDATE);
        lexer.nextToken();
        ITable table = table();
        match(Token.KW_SET);
        lexer.nextToken();
        Identifier column = identifier();
        match(Token.OP_EQUALS);
        lexer.nextToken();
        Expression value = expressionParser.expression();
        //
        List<Pair<Identifier, Expression>> values = new LinkedList<Pair<Identifier, Expression>>();
        values.add(new Pair<Identifier, Expression>(column, value));
        //
        if (lexer.token() == Token.PUNC_COMMA) {
            while (lexer.token() == Token.PUNC_COMMA) {
                lexer.nextToken();
                column = identifier();
                match(Token.OP_EQUALS);
                lexer.nextToken();
                value = expressionParser.expression();
                //
                values.add(new Pair<Identifier, Expression>(column, value));
            }
        }
        Expression where = null;
        if (lexer.token() == Token.KW_WHERE) {
            lexer.nextToken();
            where = expressionParser.expression();
        }
        return new UpdateStatement(table, new ArrayList<Pair<Identifier, Expression>>(values), where);
    }
}
